package com.study.feign;

import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * feign 调用时、把header 也传递给服务提供方
 * openFeign依赖ribbon、ribbon依赖restTemplate
 */
@Slf4j
@Configuration
public class FeignConfig {

    /**
     * 是给feign 配置请求拦截器
     * RequestInterceptor 是我们给 open-feign的请求拦截器、把header信息传递
     *
     * @return
     */
    @Bean
    public RequestInterceptor headerInterceptor() {

        return template -> {

            ServletRequestAttributes attributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

            if (null != attributes) {

                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if (null != headerNames) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        String values = request.getHeader(name);
                        //不能把当前请求的content-length 传递给下游的服务提供方
                        //请求可能一直返回不了、或者是请求响应数据被截断
                        if (!name.equalsIgnoreCase("content-length")) {
                            //template 就是restTemplate
                            template.header(name, values);
                        }
                    }
                }
            }
        };
    }
}
